import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
import client from './modules/client'
import createPersistedState from 'vuex-persistedstate'
// import createPersistedStatePlugin from './persistedStatePlugin'

const { ipcRenderer } = window.electron
import { merge } from 'lodash'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {},
  mutations: {},
  modules: {
    user,
    client
  },
  getters: {
    token: (state) => state.user.token,
    userId: (state) => state.user.userId
  },
  // plugins: [createPersistedState({ paths: ['user.token', 'user.userId'] })]
  plugins: [
    createPersistedState({
      paths: ['user.token', 'user.userId', 'client.token'], // 与 reducer 互斥，作用相同
      storage: {
        getItem: (key) => {
          return ipcRenderer.sendSync('getItem', { key })
        },
        setItem: (key, value) => {
          return ipcRenderer.sendSync('setItem', { key, value })
        },
        removeItem: (key) => {
          return ipcRenderer.sendSync('removeItem', { key })
        }
      },
      getState: (key, storage) => {
        ipcRenderer.on('persisted-changed', () => {
          const res = ipcRenderer.sendSync('getItem', { key })
          const data = res ? JSON.parse(res) : undefined
          // console.log(data)
          store.replaceState(merge(store.state, data))
        })

        const res = storage.getItem(key)
        return res ? JSON.parse(res) : undefined
      }
    })
    // 手写持久化插件
    // createPersistedStatePlugin({
    //   paths: ['user.userId', 'user.token']
    // })
  ]
})

export default store
